package com.vgooo.client.myvg;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.vgooo.bean.UserInfo;
import com.vgooo.client.Constants;
import com.vgooo.client.VGApplication;
import com.vgooo.util.DebugTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.MD5Utils;
import com.vgooo.util.UmengUtils;

/**
 * 处理用户相关信息
 * 
 * @author Administrator
 * 
 */
public class UserUtils {

	private final static String className = "UserUtils";
	private final static String USER_DB = "/user.db";
	
	
	public final static int SUCCESS = 0xfdb ;
	public final static int FAIL = SUCCESS + 1 ;

	public static boolean writeUserInfo(UserInfo user, Context context) {
		String file = getFileDir();
		if (user == null || file == null) {
			return false;
		}
		file += USER_DB;
		ObjectOutputStream oos = null;
		try {
			File f = new File(file);
			oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(user);
			DebugTools.log(className, "保存用户信息成功！   " + user);
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			UmengUtils.onError(context, "保存用户信息失败：" + e.toString());
			return false;
		} finally {
			try {
				if (oos != null)
					oos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
			}

		}

	}

	public static UserInfo readUserInfo(Context context) {
		String file = getFileDir();
		if (file == null) {
			DebugTools.log(className, "读取用户信息失败***！   ");
			return null;
		}
		file += USER_DB;
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(file));
			UserInfo user = (UserInfo) ois.readObject();
			DebugTools.log(className, "读取用户信息成功！   " + user);
			return user;
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			UmengUtils.onError(context, "读取用户信息失败：" + e.toString());
			return null;
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static String getFileDir() {
		if (VGApplication.file == null) {
			return null;
		} else {
			return VGApplication.file;
		}
	}

	/**
	 * 用户修改密码
	 * 
	 * @param password
	 *            新密码
	 * @return boolean true 修改成功 false 修改失败
	 */
	public static void chanagePassWord(String password, Context context , Handler handler) {
		ChangePW cpw = new ChangePW(password, context ,handler);
		cpw.execute("");
	}

	private static class ChangePW extends AsyncTask<String, String, String> {
		private String password;
		private Context context;
		private Handler handler ;
		int result = -1;

		public ChangePW(String password, Context context ,Handler handler) {
			super();
			this.password = password;
			this.context = context;
			this.handler = handler ;
			
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Message msg = Message.obtain();
			try {
				
				Map<String,String> parmas = new HashMap<String, String>();
				String uid = VGApplication.userInfo.user_id ;
				String code = MD5Utils.getMD5(uid
						+ MD5Utils.getMD5("updatevgoooprofile" + uid));
				parmas.put("uid", uid);
				parmas.put("code", code);
				parmas.put("password", password);
				String urlPath = HttpUtils.BASE_URI +"updateprofile" ;
				System.out.println("urlPath : " + urlPath);
				String result = HttpUtils.doPost(urlPath, parmas);
				if("1".equals(result)){
					msg.what = SUCCESS ;
				}else{
					msg.what = FAIL ;
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				UmengUtils.onError(context, "修改密码失败！  " + e.toString());
				msg.what = FAIL ;
				e.printStackTrace();
			}
//			msg.obj = result ;
			handler.sendMessage(msg) ;
//			handler.handleMessage(msg);
			return null;
		}

	}

	/**
	 * 
	 * @param filePath
	 *            头像图片绝对路径
	 * @param context
	 * @return result 0：文件不存在，1：文件类型不支持，2:文件大小不正确,3：上传失败,若返回头像路径字符串则上传成功
	 */
	public static void uploadFace(String filePath, Context context , Handler handler) {
		boolean flag = false;

		ChangeFacePhone cfp = new ChangeFacePhone(filePath, context , handler);
		cfp.execute("");
	}

	private static class ChangeFacePhone extends
			AsyncTask<String, String, String> {
		String result = "";
		String filePath;
		Context context ;
		Handler handler ;

		public ChangeFacePhone(String filePath, Context context,
				Handler handler ) {
			super();
			this.filePath = filePath ;
			this.context = context ;
			this.handler = handler ;
		}


		@Override
		protected String doInBackground(String... params) {
			Message message = Message.obtain();
			try {
				File file = new File(filePath);
				String uid = VGApplication.userInfo.user_id;
				String code = MD5Utils.getMD5("uploadface" + MD5Utils.getMD5(uid));
				Map<String, ContentBody> paramss = new HashMap<String, ContentBody>();
				paramss.put("uid", new StringBody(uid));
				paramss.put("code", new StringBody(code));
				FileBody bin = null;
				if (file != null) {
					paramss.put("file", new FileBody(file));
					bin = new FileBody(file);
				} else {
					System.out.println("***********文件不存在 ************");
				}
				result = postFile(file, paramss);
				message.what = Constants.LOAD_SUCCESS;
				
//				        StringBody uid = new StringBody(id);  
//				
//				        StringBody code = new StringBody(cod);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				message.what = Constants.LOAD_FAIL;
				e.printStackTrace();
			} 
			
			message.obj = result ;
			handler.sendMessage(message);
//			handler.handleMessage(message);
			//
			////请记住，这边传递汉字会出现乱码，解决方法如下,设置好编码格式就好</SPAN><SPAN> </SPAN></SPAN>   
//			            new StringBody("汉字",Charset.forName("UTF-8")));    
			return result;
		}
		
		
		

	}

	public static String postFile(File file, Map<String, ContentBody> params)
			throws ClientProtocolException, IOException {

		String result = "";
		String url = HttpUtils.BASE_URI + "uploadface";

		HttpClient httpclient = new DefaultHttpClient();

		HttpPost httppost = new HttpPost(url);

		MultipartEntity reqEntity = new MultipartEntity();

		Set<String> keys = params.keySet();
		for (String key : keys) {
			reqEntity.addPart(key, params.get(key));
		}

		// reqEntity.addPart("uid", uid);
		//
		// reqEntity.addPart("code", code);
		//
		// reqEntity.addPart("file", bin);

		httppost.setEntity(reqEntity);

		System.out.println("执行: " + httppost.getRequestLine());

		HttpResponse response = httpclient.execute(httppost);

		System.out.println("statusCode is "
				+ response.getStatusLine().getStatusCode());

		HttpEntity resEntity = response.getEntity();

		System.out.println("----------------------------------------");

		System.out.println(response.getStatusLine());

		if (resEntity != null) {

			System.out.println("返回长度: " + resEntity.getContentLength());

			System.out.println("返回类型: " + resEntity.getContentType());

			InputStream in = resEntity.getContent();

			System.out.println("in is " + in);

			// System.out.println(IoStreamUtil.getStringFromInputStream(in));
			result = HttpUtils.changeInputStream(in);
			System.out.println(result);

		}

		if (resEntity != null) {

			resEntity.consumeContent();

		}

		return result;

	}

}
